/* eslint-disable */

import axios from 'axios'
import {
  pendingRequest,
  messageWrap,
  getCookieData,
  showErrMessage,
  clearPendingRequest,
  showSuccessMessage,
  findDefaultMessage
} from './util'
import {
  requestInterceptor,
  responseInterceptor
} from './axios.interceptor'

import { default as debug, isDebugger } from './debug'


/**
 * @options { Object } 类Request 入参
 *
 */
export class Request {
  constructor (options) {
    this.service = axios.create({
      baseURL: options.baseURL || options.baseUrl,
      timeout: 100000
    })
    this.Message = options.Message || findDefaultMessage()
    this.options = Object.assign({
      method: 'post',
      warning: true,
      cover: true,
      login: true,
      checkWarning: true,
      repeat: false,
      isAddHospitalSoid: true
    }, options)
    this.temp = this.temp.bind(this)
    this.generate = this.generate.bind(this)
    // const cookieData = Request.getCookieData()
    requestInterceptor(this.service)
    responseInterceptor(this.service)
  }

  // 设置全局Message
  get message () {
    return messageWrap.message
  }
  set message (message) {
    messageWrap.message = message
  }
  // 获取cookie 数据
  static getCookieData () {
    return getCookieData()
  }

  // pending 状态map
  static getPendingRequestMap () {
    return pendingRequest
  }
  // 清除请求
  static clear (whiteList = []) {
    return clearPendingRequest(whiteList)
  }

  static asyncClear (whiteList = []) {
    return (new Promise((resolve) => {
      resolve()
    })).then(() => {
      return clearPendingRequest(whiteList)
    })
  }

  static handle (data, options) {
    // 非debug模式
    if (!isDebugger) {
      return this.generate(data, options)
    }
    
    // debug模式 
    return debug(data).then(() => {
      return this.generate(data, options).then(res => {
        if (isDebugger) {
          window.document.dispatchEvent(new CustomEvent('back', {
            detail: {
              res,
              data
            }
          }))
        }
        return res
      })
    }).catch(err => {
      // debug 模式
      if (isDebugger) {
        window.document.dispatchEvent(new CustomEvent('back', {
          detail: {
            res: err,
            data
          }
        }))
      }
    })
  }

  generate (data, options) {
    return this.service(data).then((res) => {
      const { successTxt, warning } = options
      if (res.success) {
        // 接口成功且配置了成功文案
        successTxt && (showSuccessMessage(this.Message, options))
        return res
      } else {
        // 接口失败且允许自动报错
        if (warning) {
          res.errorDetail.id = res.traceid
          res.errorDetail.path = data.url
        }
        return Promise.reject(res)
      }
    }).catch(err => {
      // 接口请求中发生未知错误
      const { errorDetail } = err
      if (options.warning && errorDetail && errorDetail.message) {
        showErrMessage(this.Message, errorDetail, options)
      }
      return Promise.reject(err)
    })
  }

  temp (url, config = {}) {
    return (data, customer) => {
      const options = Object.assign({}, this.options, config, customer)
      const handle = this ? Request.handle.bind(this) : Request.handle
      const { method } = options
      return handle({
        url,
        method,
        options,
        [method === 'post' ? 'data' : 'params']: data
      }, options)
    }
  }
}

export default Request
